package com.lcn.comm.framework.task;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>类说明</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @create: 2017-12-25 11:55
 */
public class TaskGroupManager {

    private static TaskGroupManager instance = null;

    private static Map<String, TaskGroup> taskMap = new ConcurrentHashMap<String, TaskGroup>();

    private TaskGroupManager() {
    }

    public static TaskGroupManager getInstance() {
        if (instance == null) {
            synchronized (TaskGroupManager.class) {
                if (instance == null) {
                    instance = new TaskGroupManager();
                }
            }
        }
        return instance;
    }

    /**
     * 创建task
     *
     * @param groupId
     * @param requestId
     * @return
     */
    public TxTask createTask(String groupId, String requestId) {
        TaskGroup taskGroup = getTaskGroup(groupId);
        if (taskGroup == null) {
            taskGroup = new TaskGroup();
        }
        taskGroup.setGroupId(groupId);
        TxTask txTask = new TxTask(ConditionUtils.getInstance().createTask(requestId));
        txTask.setGroupId(groupId);
        txTask.setRequestId(requestId);
        taskGroup.addTask(txTask);
        taskMap.put(groupId, taskGroup);
        return txTask;
    }

    /**
     * 获取task
     *
     * @param groupId
     * @param requestId
     * @return
     */
    public TxTask getTask(String groupId, String requestId) {
        TaskGroup taskGroup = taskMap.get(groupId);
        if (taskGroup != null && !taskGroup.getTaskMap().isEmpty()) {
            return taskGroup.getTaskMap().get(requestId);
        }
        return null;
    }

    /**
     * 获取task任务组
     *
     * @param groupId
     * @return
     */
    public TaskGroup getTaskGroup(String groupId) {
        return taskMap.get(groupId);
    }

    /**
     * 删除任务组
     *
     * @param groupId
     */
    public void removeKey(String groupId) {
        if (StringUtils.isNotEmpty(groupId)) {
            taskMap.remove(groupId);
        }
    }
}
